package com.test.event.config;

import com.test.event.listener.EventListener;
import com.test.event.service.EventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class EventWatcher implements SmartLifecycle {

    private final AtomicBoolean running = new AtomicBoolean(false);

    private EventService eventService;

    private Map<String, EventListener> eventListenerMap;

    @Autowired
    public void setEventService(EventService eventService) {
        this.eventService = eventService;
    }

    @Autowired
    public void setEventListenerMap(Map<String, EventListener> eventListenerMap) {
        this.eventListenerMap = eventListenerMap;
    }

    @Override
    public void start() {
        if (this.running.compareAndSet(false, true)) {
            log.debug("start register listener...");
            eventListenerMap.entrySet()
                    .forEach(entry -> eventService.subscribe(entry.getKey(), entry.getValue()));
        }
    }

    @Override
    public void stop() {
        if (this.running.compareAndSet(true, false)) {
            log.debug("stopped listener...");
            eventListenerMap.keySet().forEach(key -> eventService.unsubscribe(key));
        }
    }

    @Override
    public boolean isRunning() {
        return this.running.get();
    }
}
